//
//  ViewController.m
//  Bluetooth Tests
//
//  Created by Zack Brody on 7/13/13.
//  Copyright (c) 2013 Zack Brody. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize currentSession;
@synthesize connect;
@synthesize disconnect;

GKPeerPickerController *picker;

- (void)viewDidLoad
{
    [connect setHidden:NO];
    [disconnect setHidden:YES];
    [super viewDidLoad];
    image = [[UIImage alloc]init];
    image = [UIImage imageNamed:@"ball.png"];
    image2 = [[UIImage alloc]init];
    image2 = [UIImage imageNamed:@"ball2.png"];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.033 target:self selector:@selector(update) userInfo:nil repeats:YES];
    particles = [[NSMutableArray alloc]init];
    previousPoint = CGPointMake(160, 240);
    self.view.multipleTouchEnabled = TRUE;
    self.view.frame = [[UIScreen mainScreen]bounds];
}


-(IBAction) btnConnect:(id) sender {
    picker = [[GKPeerPickerController alloc] init];
    picker.delegate = self;
    picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
    [connect setHidden:YES];
    [disconnect setHidden:NO];
    [picker show];
}

- (void)peerPickerController:(GKPeerPickerController *)picker
              didConnectPeer:(NSString *)peerID
                   toSession:(GKSession *) session {
    self.currentSession = session;
    session.delegate = self;
    [session setDataReceiveHandler:self withContext:nil];
    picker.delegate = nil;
    
    [picker dismiss];
}

- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker
{
    picker.delegate = nil;
    
    [connect setHidden:NO];
    [disconnect setHidden:YES];
}

-(IBAction) btnDisconnect:(id) sender {
    [self.currentSession disconnectFromAllPeers];
    currentSession = nil;
    
    [connect setHidden:NO];
    [disconnect setHidden:YES];
}

- (void)session:(GKSession *)session
           peer:(NSString *)peerID
 didChangeState:(GKPeerConnectionState)state {
    switch (state)
    {
        case GKPeerStateConnected:
            NSLog(@"connected");
            break;
        case GKPeerStateDisconnected:
            NSLog(@"disconnected");
            currentSession = nil;
            
            [connect setHidden:NO];
            [disconnect setHidden:YES];
            break;
        case GKPeerStateAvailable:
        case GKPeerStateConnecting:
        case GKPeerStateUnavailable:
            break;
    }
}

- (void) mySendDataToPeers:(NSData *) data
{
    if (currentSession)
        [self.currentSession sendDataToAllPeers:data
                                   withDataMode:GKSendDataReliable
                                          error:nil];
}

-(IBAction) btnSend:(id) sender
{
    //---convert an NSString object to NSData---

   // [self mySendDataToPeers:data];
}


- (void) receiveData:(NSData *)data
            fromPeer:(NSString *)peer
           inSession:(GKSession *)session
             context:(void *)context {
    
    //---convert the NSData to NSString---
    NSMutableArray *particleInfo = [[NSMutableArray alloc]initWithArray:[[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:@" "]];
    [particleInfo removeLastObject];
    dataString = [[NSString alloc]initWithFormat:@""];
    for (int i = 0; i < particleInfo.count; i += 4) {
            Particle *particle = [[Particle alloc]init:image];
            particle.image.center = CGPointMake([[particleInfo objectAtIndex:i]floatValue], [[particleInfo objectAtIndex:(i + 1)]floatValue]);
            particle.velocityX = [[particleInfo objectAtIndex:(i + 2)]floatValue];
            particle.velocityY = [[particleInfo objectAtIndex:(i + 3)]floatValue];
            particle.lifetime = arc4random() % 10 + 30;
            [particles addObject:particle];
            [self.view addSubview:particle.image];
        dataString = [dataString stringByAppendingString:[NSString stringWithFormat:@"%f %f %f %f ", particle.image.center.x, particle.image.center.y, particle.velocityX, particle.velocityY]];
    }
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    touchesArray = [NSMutableArray arrayWithArray:[touches allObjects]];
    nNumTouches = [touchesArray count];
    for (int nTouch = 0;  nTouch < nNumTouches;  nTouch++)
    {
        touch = [touchesArray objectAtIndex:nTouch];
        ptTouch = [touch locationInView:self.view];
    }
    
    touch = [touches anyObject];
    point = [touch locationInView:self.view];
    
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    dataString = [[NSString alloc]initWithFormat:@""];
    touchesArray = [NSMutableArray arrayWithArray:[touches allObjects]];
    nNumTouches = [touchesArray count];
    for (int i = 0; i < nNumTouches; i++) {;
        ptTouch = [[touchesArray objectAtIndex:i] locationInView:self.view];
        previousPoint = [[touchesArray objectAtIndex:i] previousLocationInView:self.view];
        int particlesToSpawn = 5;
        int maxLifeTime = 10;
        for (int i = 0; i < particlesToSpawn; i++) {
            Particle *particle = [[Particle alloc]init:image];
            particle.image.center = ptTouch;
            particle.velocityX = (previousPoint.x - ptTouch.x);
            particle.velocityY = (previousPoint.y - ptTouch.y);
            particle.lifetime = arc4random() % maxLifeTime + 30;
            [particles addObject:particle];
            [self.view addSubview:particle.image];
            dataString = [dataString stringByAppendingString:[NSString stringWithFormat:@"%f %f %f %f ", particle.image.center.x, particle.image.center.y, particle.velocityX, particle.velocityY]];
        }
        
    }
    [self mySendDataToPeers:[dataString dataUsingEncoding:NSASCIIStringEncoding]];
}
- (void) update
{
    int i = 0;
    while (i < particles.count) {
        Particle *p = [particles objectAtIndex:i];
        if([p isAlive])
        {
            [p update:image];
            
            i++;
        } else {
            [p.image removeFromSuperview];
            [particles removeObject:p];
        }
    }
}

@end